package com.yaodian100.ec.member.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;

import com.huangzhimin.contacts.Contact;
import com.huangzhimin.contacts.ContactsImporter;
import com.huangzhimin.contacts.ContactsImporterFactory;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.mail.entity.Mail;
import com.yaodian100.core.mail.service.MailService;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.ec.common.EnvParameters;
import com.yaodian100.ec.member.entity.SnsLog;
import com.yaodian100.ec.member.service.SnsService;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.service.ProductService;
import com.yaodian100.ec.shelf.entity.Shelf;

/**
 * @author afra.chou
 * 
 */
public class SnsServiceImpl extends DomainServiceImpl<SnsLog> implements SnsService {
	@Resource
	private MailService mailService;
	@Resource
	private TemplateService velocityService;
	@Resource
	private EnvParameters envParameters;
	@Resource
	private ProductService productService;
	@Resource
	private BaseManager baseMgr;

	public List<Contact> getContacts(String userName, String password, String type) {
		List<Contact> contacts = new ArrayList<Contact>();

		try {
			ContactsImporter importer = null;
			if ("gmail".equals(type))
				importer = ContactsImporterFactory.getGmailContacts(userName, password);
			else if ("163".equals(type))
				importer = ContactsImporterFactory.getOneSixThreeContacts(userName, password);
			else if ("sohu".equals(type))
				importer = ContactsImporterFactory.getSohuContacts(userName, password);
			else if ("sina".equals(type))
				importer = ContactsImporterFactory.getSinaContacts(userName, password);
			contacts = importer.getContacts();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return contacts;
	}

	@Transactional(readOnly = false)
	public void sendMail(String contacts, String pageType, String pageData, String snsTypes) {
		// 紀錄分享的動作
		String[] snstype = StringUtils.split(snsTypes, ",");
		for (int i = 0; i < snstype.length; i++) {
			SnsLog sns = new SnsLog();
			sns.setPageType(pageType);
			sns.setPageData(pageData);
			sns.setSnsType(snstype[i]);
			sns = this.save(sns);
		}

		Map<String, Object> contentMap = new HashMap<String, Object>();
		String velocityTemplate = "";
		// 分享商品
		if ("PRD".equals(pageType)) {

			Product product = productService.get(pageData);
			if (null != product) {
				velocityTemplate = "sharedProduct";

				Date currentDate = new Date();
				DetachedCriteria dc = DetachedCriteria.forClass(Shelf.class);
				dc.add(Restrictions.eq("productId", product.getProductId()));
				dc.add(Restrictions.le("startDate", currentDate));
				dc.add(Restrictions.ge("endDate", currentDate));
				dc.add(Restrictions.eq("shelfStatus", "SHF500"));
				Object[] shelfs = baseMgr.findByCriteria(dc, 0, 1);
				String promoName = "";
				if (shelfs.length > 0) {
					promoName = ((Shelf) shelfs[0]).getPromoteName();
				}

				contentMap.put("prodBrief", productService.readFromFile(pageData, "brief"));
				contentMap.put("product", product);
				contentMap.put("promoName", promoName);
				contentMap.put("imgUrl", ServerValue.getImgDomain() + "/PImg/" + product.getProductId().substring(0, 4) + "/"
						+ product.getProductId() + "/" + product.getProductId() + "_m135.jpg");

			}

		}
		// 分享活動
		if ("MKT".equals(pageType)) {
			velocityTemplate = "sharedMarketing";
			contentMap.put("srcURL", pageData);
			String pageTitle = getPageTitle(pageData);
			if (StringUtils.isNotBlank(pageTitle)) {
				contentMap.put("pageTitle", pageTitle);
			} else {
				contentMap.put("pageTitle", "");
			}

		}

		// 發送信件
		if (StringUtils.isNotBlank(velocityTemplate)) {
			String[] contact = StringUtils.split(contacts, ",");
			for (int i = 0; i < contact.length; i++) {
				sendShareMail(velocityTemplate, contentMap, contact[i].trim());

			}
		}

	}

	@Transactional(readOnly = false)
	public void sendShareMail(String velocityTemplate, Map<String, Object> contentMap, String contact)
			throws CoreException {
		try {

			contentMap.put("customerFax", ServerValue.getCustomerFax());
			contentMap.put("customerTel", ServerValue.getCustomerTel());
			contentMap.put("contextpath", ServerValue.getFrontContextPath());
			contentMap.put("basehref", ServerValue.getFrontHostname());

			Mail mail = velocityService.formatToMail(velocityTemplate, contentMap);
			mail.setTo(contact);
			mail.setFrom(envParameters.getEmailFromSharing());
			mail.setSubject("嗨，我在耀点100发现了个好东东分享给你～");
			mailService.save(mail);
		} catch (Exception e) {
			logger.error("err:" + e.getMessage());
		}
	}

	private String getPageTitle(String urlStr) {
		String pageTitle = "";
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.connect();
			if (conn.getResponseCode() == 200) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
				String html = "", tmp = "";
				while ((tmp = reader.readLine()) != null) {
					html += " " + tmp;
				}
				reader.close();

				html = html.replaceAll("\\s+", " ");
				Pattern p = Pattern.compile("<title>(.*?)</title>");
				Matcher m = p.matcher(html);
				while (m.find() == true) {
					pageTitle = m.group(1);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return pageTitle;
	}

}